<template>
  <div class="article-list">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
          <template #icon>
            <van-image
              v-if="article.coverImage"
              :src="article.coverImage"
              width="80"
              height="60"
              fit="cover"
              radius="4"
            />
          </template>

          <template #label>
            <div class="article-info">
              <div class="meta">
                <span>{{ article.author }}</span>
                <span>{{ formatDate(article.createTime) }}</span>
                <span>阅读 {{ article.viewCount }}</span>
              </div>
            </div>
          </template>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { getArticleList } from '@/api/article'
import { showToast } from 'vant'

const props = defineProps({
  categoryId: {
    type: Number,
    default: null
  }
})

const current = ref(1)
const articles = ref([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)

const loadArticles = async () => {
  try {
    const { data } = await getArticleList({
      current: current.value,
      size: 10,
      categoryId: props.categoryId
    })

    if (refreshing.value) {
      articles.value = []
      refreshing.value = false
    }

    articles.value.push(...data.records)
    loading.value = false

    if (articles.value.length >= data.total) {
      finished.value = true
    } else {
      current.value += 1
    }
  } catch (error) {
    showToast('获取文章列表失败')
    loading.value = false
  }
}

const onLoad = () => {
  loadArticles()
}

const onRefresh = () => {
  finished.value = false
  current.value = 1
  loadArticles()
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    month: 'numeric',
    day: 'numeric'
  })
}
</script>

<style lang="scss" scoped>
.article-list {
  .article-info {
    .summary {
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      color: #666;
      font-size: 14px;
      line-height: 1.4;
      margin: 4px 0;
    }

    .meta {
      display: flex;
      gap: 12px;
      color: #999;
      font-size: 12px;
    }
  }
}
</style>
